#!/usr/bin/python
# encoding: utf-8
import re
from django.conf import settings
from django.contrib.gis.db import models

STATUS_CHOICES = (
    (0, u"Fluido"),
    (1, u"Pesado"),
    (2, u"Lento"),
    (3, u"Muy lento"),
    (4, u"Parado"),
)

class UnknowStatusChoiceError(Exception):
    pass
        
class City(models.Model):
    name = models.CharField(blank=False, max_length=100)
    
    class Meta:
        app_label = 'mobile'
        
    def __unicode__(self):
        return self.name

class Entry(models.Model):
    name = models.CharField(blank=False, max_length=100)
    label = models.CharField(blank=False, max_length=100)
    city = models.ForeignKey(City)
    
    class Meta:
        app_label = 'mobile'
    
    def discover_status(self, estado):
        for s in STATUS_CHOICES:
            if s[1] == estado:
                return s[0]
        raise UnknowStatusChoiceError()
        
    def set_estado(self, estado):
        estado = estado.strip()
        try:
            estado = self.discover_status(estado)
        except:
            return
        
        es = EntryStatus(entry=self, status=estado)
        es.save()
    
    def get_last_capture(self):
        return EntryStatus.objects.filter(entry=self).order_by('-created')[:1][0]
    
    def get_cameras(self):
        return EntryCamera.objects.filter(entry=self)
        
    def __unicode__(self):
        return u"%s" % (self.name)

class EntryStatus(models.Model):
    entry = models.ForeignKey(Entry)
    created = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(blank=False, null=False, choices=STATUS_CHOICES)
    
    class Meta:
        app_label = 'mobile'
        
    def __unicode__(self):
        return u"%s [%s] %s" % (self.entry, self.get_status_display(), self.created)

class EntryCamera(models.Model):
    entry = models.ForeignKey(Entry)
    name = models.CharField(blank=False, max_length=100)
    url = models.CharField(blank=False, max_length=300)
    
    class Meta:
        app_label = 'mobile'
        
    def __unicode__(self):
        return u"%s %s" % (self.entry, self.name)